/*	******************************************
	File:		SoundTracker.cpp
	Author:		Adnan Srna, Peter Kober, Ivo Havranek
	Purpose:	AugmentedReality 2
	(up)Date:	March/April 2010
	Descr.:		function for sound tracking 
	Origin:		Salzburg University of Applied Science
	******************************************	*/

#include "SoundTracker.h"

CSound::CSound(){}

CSound::~CSound(){
	ofSoundStreamStop();	
}

void CSound::setup(){
	//cout<<"Yeah!"<<endl;
	srand((unsigned int)time((time_t *)NULL));
	
	// 0 output channels, 2 input channels
	// 44100 samples per second
	// BUFFER_SIZE samples per buffer, 4 num buffers (latency)
	
	ofSoundStreamSetup(0, 2, this, 44100, BUFFER_SIZE, 4);
	left = new float[BUFFER_SIZE];
	right = new float[BUFFER_SIZE];

	for (int i = 0; i < NUM_WINDOWS; i++)
	{
		for (int j = 0; j < BUFFER_SIZE/2; j++)
		{
			freq[i][j] = 0;	
		}
	}
	amplitude=0;
}

// do the FFT calculation
void CSound::update(){
	static int index=1;
	float avg_power = 0.0f;
	amplitude = 0;

	myfft.powerSpectrum(0,(int)BUFFER_SIZE/2, left,BUFFER_SIZE,&magnitude[0],&phase[0],&power[0],&avg_power);
	
	/* start from 1 because mag[0] = DC component */
	/* and discard the upper half of the buffer */
	for(int j=1; j < BUFFER_SIZE/2; j++) {
		freq[index][j] = magnitude[j];
		
		if (magnitude[j] > amplitude)
			amplitude = magnitude[j];
	}
}


// draw the FFT
void CSound::draw(){
	ofSetColor(255, 250, 250);
	ofSetLineWidth(3);

	for (int i = 1; i < (int)(BUFFER_SIZE/2); i++){
		ofLine(5+(i*8), ofGetHeight()-200, 5+(i*8), ofGetHeight()-200-magnitude[i]*10.0f);
	}
}

void CSound::audioReceived(float * input, int bufferSize, int nChannels){	
	// samples are "interleaved"
	for (int i = 0; i < bufferSize; i++){
		left[i] = input[i*2];
		right[i] = input[i*2+1];
	}
	bufferCounter++;
}